package com.example.common.domain.pojo.TypeHandler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JsonToObject {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public Map<String, String> parseToMap(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readValue(json, Map.class);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON to map", e);
        }
    }


    public Map<String, List<String>> parseToMapList(String json) {
        try {
            if (json == null || json.isEmpty()) {
                return new HashMap<>();
            }
            return objectMapper.readValue(json,
                    new TypeReference<Map<String, List<String>>>() {
                    });
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON to Map<String, List<String>>", e);
        }
    }
    public List<Object> parseToList(String json) {
        try {
            if (json == null || json.trim().isEmpty()) {
                return null;
            }
            return objectMapper.readValue(json, List.class);
        } catch (Exception e) {
            throw new RuntimeException("解析JSON失败: " + json, e);
        }
    }

    public String toJson(Object obj) {
        try {
            if (obj == null) {
                return null;
            }
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("转换对象为JSON失败", e);
        }
    }



}
